//
//  WeatherViewController.m
//  Zaker
//
//  Created by dllo on 16/3/17.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "WeatherViewController.h"

@interface WeatherViewController ()

@property (nonatomic, retain) UIImageView *backImage;
@property (nonatomic, retain) UILabel *cityLabel;
@property (nonatomic, retain) UILabel *temperature;
@property (nonatomic, retain) UILabel *date;
@property (nonatomic, retain) UILabel *weatherLabel;
@property (nonatomic, retain) UIButton *locate;
@property (nonatomic, retain) UIView *backView;
@property (nonatomic, retain) NSMutableArray *lineArr;

@end

@implementation WeatherViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    //[self createWeather];
}

- (void)createWeather
{
    self.temperature = [[UILabel alloc] initWithFrame:CGRectMake(0, 120 * HEIGHT, SCREEN_WIDTH, 80 * HEIGHT)];
    self.temperature.textColor = [UIColor whiteColor];
    self.temperature.textAlignment = NSTextAlignmentCenter;
    self.temperature.font = [UIFont systemFontOfSize:40];
    [self.view addSubview:self.temperature];
    
    self.date = [[UILabel alloc] initWithFrame:CGRectMake(0, 220 * HEIGHT, SCREEN_WIDTH, 40 * HEIGHT)];
    self.date.textColor = [UIColor whiteColor];
    self.date.textAlignment = NSTextAlignmentCenter;
    self.date.font = [UIFont systemFontOfSize:20];
    [self.view addSubview:self.date];
    
    self.weatherLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 280 * HEIGHT, SCREEN_WIDTH, 20 * HEIGHT)];
    self.weatherLabel.textColor = [UIColor whiteColor];
    self.weatherLabel.textAlignment = NSTextAlignmentCenter;
    self.weatherLabel.font = [UIFont systemFontOfSize:20];
    [self.view addSubview:self.weatherLabel];
}

- (void)requestWeather
{
    NSString *city = @"";
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"city"]) {
        city = [[NSUserDefaults standardUserDefaults] valueForKey:@"city"];
    } else {
        city = @"大连";
    }
    
    self.cityLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 40, SCREEN_WIDTH, 30)];
    _cityLabel.text = city;
    _cityLabel.textColor = [UIColor whiteColor];
    _cityLabel.textAlignment = 1;
    _cityLabel.font = [UIFont systemFontOfSize:22];
    
    //实例化一个回调，处理请求的返回值
    APISCallBack* callBack = [APISCallBack alloc];
    
    callBack.onSuccess = ^(long status, NSString *responseString) {
        NSLog(@"onSuccess");
        if(responseString != nil) {
            //_resultText.text = [@"success\n" stringByAppendingString: responseString];
            NSData *data = [responseString dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSDictionary *dic = [result[@"HeWeather data service 3.0"] firstObject];
            WeatherModel *model = [WeatherModel modelWithDic:dic];
            [self createWeather];
            _temperature.text = [NSString stringWithFormat:@"%@°", model.nowTmp];
            NSString *str = [model.loc substringToIndex:10];
            _date.text = str;
            _weatherLabel.text = [NSString stringWithFormat:@"%@ | 空气%@", model.txt, model.qlty];
            self.lineArr = [LineModel modelHandlerWithArray:model.daily_forecast];
            [self createLineView];
        }
    };
    
    callBack.onError = ^(long status, id responseString) {
        NSLog(@"onError");
        //_resultText.text = [@"error\n" stringByAppendingString: responseString];
        NSLog(@"%@", responseString);
    };
    
    callBack.onComplete = ^() {
        NSLog(@"onComplete");
    };
    
    //部分参数
    NSString *uri = @"http://apis.baidu.com/heweather/weather/free";
    NSString *method = @"post";
    NSMutableDictionary *parameter = [[NSMutableDictionary alloc] init];
    [parameter setObject:city forKey:@"city"];
    
    //请求API
    [ApiStoreSDK executeWithURL:uri method:method apikey:@"f0eba1db9cf1031ae1a9b1bb72686777" parameter:parameter callBack:callBack];
}

- (void)createLineView
{
    UIView *blackView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 220, SCREEN_WIDTH, 220)];
    [self.view addSubview:blackView];
    blackView.backgroundColor = [UIColor blackColor];
    blackView.alpha = 0.2;
    
    UIBezierPath *firstPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, SCREEN_HEIGHT - 80, 0, 0)];
    UIBezierPath *firstPath1 = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, SCREEN_HEIGHT - 120, 0, 0)];
    
    for (int i = 0; i < 5; i++) {
        LineModel *model = _lineArr[i];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH / 5 * i, SCREEN_HEIGHT - 60, SCREEN_WIDTH / 5, 50)];
        if (i == 0) {
            label.text = [NSString stringWithFormat:@"今天\n%@\n%@°/%@°", model.txt_d, model.maxTmp, model.minTmp];
        } else if (i == 1) {
            label.text = [NSString stringWithFormat:@"明天\n%@\n%@°/%@°", model.txt_d, model.maxTmp, model.minTmp];
        } else {
            NSString *str = [model.date substringFromIndex:5];
            label.text = [NSString stringWithFormat:@"%@\n%@\n%@°/%@°", str, model.txt_d, model.maxTmp, model.minTmp];
        }
        label.textAlignment = 1;
        label.textColor = [UIColor whiteColor];
        label.numberOfLines = 3;
        label.font = [UIFont systemFontOfSize:13];
        [self.view addSubview:label];
        
        UIColor *color = [UIColor whiteColor];
        [color set];
        
        NSInteger min = model.minTmp.integerValue;
        NSInteger max = model.maxTmp.integerValue;
        //四个点
        CGPoint pointMin = CGPointMake(SCREEN_WIDTH / 5 * (i + 0.5), SCREEN_HEIGHT - 70 - min * 7);
        CGPoint pointMax = CGPointMake(SCREEN_WIDTH / 5 * (i + 0.5), SCREEN_HEIGHT - 70 - max * 7);
        
        [firstPath1 addLineToPoint:pointMax];
        [firstPath addLineToPoint:pointMin];
    }
    
    [firstPath1 addLineToPoint:CGPointMake(SCREEN_WIDTH + 10, SCREEN_HEIGHT - 140)];
    [firstPath addLineToPoint:CGPointMake(SCREEN_WIDTH, SCREEN_HEIGHT - 100)];
    
    CAShapeLayer *lineLayerMax = [CAShapeLayer layer];
    lineLayerMax.fillColor = [UIColor clearColor].CGColor;
    lineLayerMax.path = firstPath1.CGPath;
    lineLayerMax.strokeColor = [UIColor whiteColor].CGColor;
    CABasicAnimation *aniM = [CABasicAnimation animationWithKeyPath:NSStringFromSelector(@selector(strokeEnd))];
    aniM.fromValue = @0;
    aniM.toValue = @1;
    aniM.duration = 2;
    [lineLayerMax addAnimation:aniM forKey:NSStringFromSelector(@selector(strokeEnd))];
    [self.view.layer addSublayer:lineLayerMax];
    
    CAShapeLayer *lineLayer = [CAShapeLayer layer];
    lineLayer.fillColor = [UIColor clearColor].CGColor;
    lineLayer.path = firstPath.CGPath;
    lineLayer.strokeColor = [UIColor whiteColor].CGColor;
    CABasicAnimation *ani = [CABasicAnimation animationWithKeyPath:NSStringFromSelector(@selector(strokeEnd))];
    ani.fromValue = @0;
    ani.toValue = @1;
    ani.duration = 2;
    [lineLayer addAnimation:ani forKey:NSStringFromSelector(@selector(strokeEnd))];
    [self.view.layer addSublayer:lineLayer];
}

- (void)createBackImage
{
    self.backImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH + 1000 * WIDTH, SCREEN_HEIGHT)];
    self.backImage.image = [UIImage imageNamed:@"3D0BA148-FC89-43FA-9022-7B9A30A580AC副本"];
    [self.view addSubview:self.backImage];
    [UIView transitionWithView:_backImage duration:12 options:UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse animations:^{
        self.backImage.frame = CGRectMake(-1000 * WIDTH, 0, SCREEN_WIDTH + 1000 * WIDTH, SCREEN_HEIGHT);
    } completion:^(BOOL finished) {
        
    }];
    
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(20 * WIDTH, 40, 30 * WIDTH, 30 * WIDTH);
    [leftButton setImage:[UIImage imageNamed:@"iconfont-jiantou"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:leftButton];
    
    self.locate = [UIButton buttonWithType:UIButtonTypeCustom];
    _locate.frame = CGRectMake(SCREEN_WIDTH - 50, 40, 30, 30);
    [_locate setImage:[UIImage imageNamed:@"iconfont-dingwei-2"] forState:UIControlStateNormal];
    [_locate addTarget:self action:@selector(changeLocate) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_locate];
}

- (void)changeLocate
{
    LocationViewController *locate = [[LocationViewController alloc] init];
    [self.navigationController pushViewController:locate animated:NO];
}

- (void)buttonClick
{
    [self.navigationController popViewControllerAnimated:NO];
}

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES;
    
    [self requestWeather];
    
    [self createBackImage];
    
    [self.view addSubview:_cityLabel];
}

- (void)viewWillDisappear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
